package com.example.traning.mall.framework.security.core.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Map;

import static com.example.traning.mall.framework.common.ex.GlobalErrorCodeConstants.AUTH_PARSE_ERROR;
import static com.example.traning.mall.framework.common.ex.ServiceExceptionUtil.exception;

/**
 * @author lei yu
 * @since 2024/10/14
 */
@Slf4j
@UtilityClass
public class JwtUtils {

    /**
     * jwt密钥
     */
    private String secret = "fDSwAbFLJa438AF72D73aKJDDf";

    /**
     * 单位：秒
     */
    private long expiration = 24 * 60 * 60;


    public static void init(String secret, long expiration) {
        log.info("初始化 JwtUtils");
        JwtUtils.secret = secret;
        JwtUtils.expiration = expiration;
    }

    /**
     * 根据用户信息生成token
     */
    public String generate(Map<String, Object> claims) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expireTime = now.plusSeconds(expiration);

        Map<String, Object> payload = MapUtil.<String, Object>builder()
                // 签发时间
                .put(JWTPayload.ISSUED_AT, now)
                // 过期时间
                .put(JWTPayload.EXPIRES_AT, expireTime)
                // 生效时间
                .put(JWTPayload.NOT_BEFORE, now)
                // SUBJECT
                .put(JWTPayload.SUBJECT, "sub")
                .putAll(claims)
                .build();
        return JWTUtil.createToken(payload, secret.getBytes());
    }


    /**
     * 从token中获取JWT中的负载
     */
    public JWT parse(String token) {
        JWT jwt = null;
        try {
            jwt = JWTUtil.parseToken(token).setKey(secret.getBytes());
        } catch (Exception e) {
            throw exception(AUTH_PARSE_ERROR);
        }
        // 验证，token 正确性以及是否过期，容忍 10 秒
        jwt.validate(10);
        return jwt;
    }




}
